package com.chinaedu.oc.sdk.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.chinaedu.oc.sdk.bo.Sign;
import com.chinaedu.oc.sdk.result.Result;




/**
 * 发送请求
 * @Description: TODO
 * @author A18ccms a18ccms_gmail_com 
 * @date 2017年5月9日 下午2:17:43 
 *
 */
public class SendRequest {
	
	/**
	 * url：地址
	 * key:秘钥
	 * obj：参数
	 * 
	 */
	public Result send(Sign sign, Object paramData, String path) {
		
		String data = JSON.toJSONString(paramData);
		
		String param = "";
		
		param += "data=" + data +"&";
		param += "sign=" + sign.getSign() + "&";
		param += "currentMill=" + sign.getCurrentMill() + "&";
		
		String result = this.request(path, param);
		
		return JSON.parseObject(result, Result.class);
	}
	
	private String request(String path, String paramData) {
		//System.out.println(paramData);
		URL url = null;
		try {
			url = new URL(path);
			HttpURLConnection http = (HttpURLConnection) url.openConnection();
			http.setRequestMethod("POST");
			http.setRequestProperty("accept", "*/*");  
			http.setRequestProperty("connection", "Keep-Alive");  
			
			http.setDoOutput(true);
			http.setDoInput(true);
			
			PrintWriter pw = new PrintWriter(http.getOutputStream());
			pw.write(paramData);//post的参数 xx=xx&yy=yy
			pw.flush();
			
			InputStream is = http.getInputStream();
			
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			
			String result = "";
			String line = null;
			while((line = br.readLine()) != null) {
				result += line;
			}
			
			return result;
			
			
		} catch (Exception e) {
			e.printStackTrace();
			
			return "";
		}
	}
}
